<template>
  <div class="app-container">
    <div class="filter-container">
      <!--      <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item"-->
      <!--                @keyup.enter.native="handleFilter"/>-->
      <span class="filter-item" style="margin-right: 20px">选择的电表是： {{ selectAmmeterName }}</span>
      <el-date-picker
        v-model="startTime"
        type="datetime"
        placeholder="选择开始时间"
        class="filter-item"
        align="right"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        @change="startSend"
      />
      <el-date-picker
        v-model="endTime"
        type="datetime"
        placeholder="选择结束时间"
        class="filter-item"
        align="right"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="margin-right: 50px"
        :picker-options="pickerOptions"
        @change="startSend"
      />

      <el-radio-group
        v-for="item in [{id:1,name:'15分钟'},{id:2,name:'1小时'},{id:3,name:'本日'},{id:4,name:'本周'}]"
        :key="item.id"
        v-model="selectDuring"
        class="filter-item"
        style="margin-left: 5px"
        @change="duringChoose"
      >
        <el-radio-button :label="item.id">{{ item.name }}</el-radio-button>

      </el-radio-group>
    </div>

    <!--    内容区域-->
    <div class="wrap">
      <div id="left">
        <el-tree
          :data="orgDevice"
          node-key="id"
          :expand-on-click-node="false"
          :default-expanded-keys="exKey"
          :default-checked-keys="[5]"
          :props="defaultProps"
          @node-click="selectKey"
        />
      </div>
      <div id="right">
        <div class="chart-wrapper">
          <!--          <bar-chart/>-->
          <line-chart :chart-data="lineChartData"/>
        </div>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @sort-change="sortChange"
        >
          <el-table-column
            label="序号"
            prop="id"
            sortable="custom"
            align="center"
            width="80"
            :class-name="getSortClass('id')"
          >
            <template slot-scope="{row}">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="编码"
            prop="ammeterNo"
            sortable="custom"
            align="center"
            width="80"
            :class-name="getSortClass('ammeterNo')"
          >
            <template slot-scope="{row}">
              <span>{{ row.ammeterNo }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="名称"
            prop="ammeterName"
            sortable="custom"
            align="center"
            width="150"
            :class-name="getSortClass('ammeterName')"
          >
            <template slot-scope="{row}">
              <span>{{ row.ammeterName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="电流"
            prop="numI"
            sortable="custom"
            align="center"
            width="80"
            :class-name="getSortClass('numI')"
          >
            <template slot-scope="{row}">
              <span>{{ row.numI }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="电压"
            prop="numV"
            sortable="custom"
            align="center"
            width="80"
            :class-name="getSortClass('numV')"
          >
            <template slot-scope="{row}">
              <span>{{ row.numV }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="额定电压"
            prop="numPowerRate"
            sortable="custom"
            align="center"
            width="120"
            :class-name="getSortClass('numPowerRate')"
          >
            <template slot-scope="{row}">
              <span>{{ row.numPowerRate }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="实时电压"
            prop="numPowerCurrentTime"
            sortable="custom"
            align="center"
            width="120"
            :class-name="getSortClass('numPowerCurrentTime')"
          >
            <template slot-scope="{row}">
              <span>{{ row.numPowerRate }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="时间"
            prop="time"
            sortable="custom"
            align="center"
            width="200"
            :class-name="getSortClass('time')"
          >
            <template slot-scope="{row}">
              <span>{{ row.time }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>
<style scoped>
  .wrap {
    margin: 0 auto;
    width: 100%;
    border: 1px solid #E6E6E6;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }

  #left {
    width: 15%;
    border-right: 1px solid #E6E6E6;
    float: left;
  }

  #right {
    width: 80%;
    margin-left: 15%;
  }
</style>
<script>
  import LineChart from '@/views/power-chart/admin/components/LineChart'
  import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import { service2 as http } from '@/utils/request'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  const calendarTypeOptions = [
    { key: 'CN', display_name: 'China' },
    { key: 'US', display_name: 'USA' },
    { key: 'JP', display_name: 'Japan' },
    { key: 'EU', display_name: 'Eurozone' }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: { Pagination, LineChart },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        orgDevice: [],
        lineChartData: {},
        selectDuring: 0,
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }]
        },
        startTime: '',
        endTime: '',
        exKey: [],
        selectAmmeterNo: 0,
        selectAmmeterName: '',
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          type: '',
          status: 'published'
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    created() {
      http({
        url: '/util/powerTime',
        method: 'get'
      }).then(res => {
        this.selectAmmeterNo = res.data.ammeterNo
        this.startTime = res.data.yesterday
        this.endTime = res.data.today
        this.getList()
      })
    },
    methods: {
      startSend() {
        this.getList()
      },
      duringChoose(index) {
        http({
          url: '/util/powerTimeSection',
          method: 'get'
        }).then(res => {
          switch (index) {
            case 1:
              this.startTime = res.data.before15Min
              break
            case 2:
              this.startTime = res.data.before1H
              break
            case 3:
              this.startTime = res.data.today0Time
              break
            case 4:
              this.startTime = res.data.thisMonday
              break
          }
          this.endTime = res.data.todayEnd
          this.getList()
        })
      },
      selectKey(a, node, c, d, e) {
        console.info('a', a)
        console.info('node', node)
        if (node.data.type != 30) return
        this.selectAmmeterName = node.data.name
        this.selectAmmeterNo = node.data.ammeterNo
        this.getList()
      },
      getList() {
        this.listLoading = true
        http({
          url: '/power/powerList',
          method: 'get',
          params: {
            page: this.listQuery.page,
            size: this.listQuery.limit,
            ammeterNo: this.selectAmmeterNo,
            startTime: this.startTime,
            endTime: this.endTime
          }
        }).then(res => {
          console.info('res')
          this.list = res.list
          this.total = res.count
          this.lineChartData = res.extraData
          this.listLoading = false
        })

        http({
          url: '/org/getOrg',
          method: 'get'
        }).then(res => {
          this.orgDevice = res.list[0].children
          this.exKey = res.extraData
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>
